package com.csair.irp.job.file.parser.aetatk;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csair.irp.job.common.util.MapUtil;
import com.csair.irp.job.file.exception.DataFileException;
import com.csair.irp.job.file.exception.DataOperaterException;
import com.csair.irp.job.file.exception.FileParseException;
import com.csair.irp.job.file.parser.base.ParseResult;
import com.csair.irp.job.file.parser.base.TxtFileMultiLineDataParser;
import com.csair.irp.job.file.task.DispatchLogPO;
import com.csair.irp.job.file.task.FileBaseinfoPO;
import com.csair.irp.job.file.parser.base.FileManagePO;
import com.csair.irp.job.file.util.CalculateUtil;
import com.csair.irp.job.file.util.EtTranUtil;
import com.csair.irp.job.file.util.FileUtil;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.csair.irp.job.common.util.MapUtil.get;
import static com.csair.irp.job.file.parser.base.FileManagePO.StateEnum;

/**
 * 旧调度有手动和自动两套解析逻辑
 * 手动解析逻辑考虑了去重操作，新调度改用数据库唯一键特性去去重
 *
 * @author liaolonglong
 */
@Component("AETFileParser")
public class AETFileParser extends TxtFileMultiLineDataParser<TicketReconDataPO> {

    @Autowired
    private TTicketReconDataService ticketReconDataService;

    /**
     * AET自动对接用户名
     */
    private static final String AUTO_USERNAME = "南航ET推送程序";


    private static final Double DOUBLE_ZERO = Double.valueOf(0);

    /**
     * 国内国际标志key值
     */
    private final String KEY_FLAG = "flag";

    /**
     * 标志是自动上传还是手动上传
     */
    private final String KEY_AUTO = "auto";

    /**
     * 用于累加每张票的所有税，解决0.01分问题。
     */
    private final String KEY_SUM_ALL_TAX = "sum_all_tax";

    /**
     * 国际的票价和税费和
     */
    private final String KEY_TOTAL_FARE_TAX = "total_fare_tax";

    private final String KEY_COUNT_TS = "count_ts";

    private final String KEY_COUNT_MR = "count_mr";

    private static final String KEY_COUNT_AS = "count_as";

    private static final String KEY_COUNT_AT = "count_at";

    private static final String KEY_COUNT_TFR = "count_tfr";

    private static final String KEY_COUNT_IR = "count_ir";

    private static final String KEY_COUNT_PR = "count_pr";

    private static final String KEY_COUNT_FC = "count_fc";

    private static final String KEY_COUNT_ED = "count_ed";

    private static final String KEY_COUNT_AI = "count_ai";

    private static final String KEY_COUNT_EC = "count_ec";

    private static final String KEY_COUNT_ER = "count_er";

    private static final String KEY_COUNT_ES = "count_es";

    private static final String KEY_COUNT_AF = "count_af";

    private static final String KEY_STINDEX = "stindex";

    private static final String KEY_DATABASE_DATA = "database_data";

    @Override
    public Map<Object, Object> initParams(DispatchLogPO dispatchLog, FileBaseinfoPO taskInfo) {
        Map<Object, Object> params = super.initParams(dispatchLog, taskInfo);

        //设置ET国内和ET国际标记，0：ET-国际，1：ET-国内
        params.put(KEY_FLAG, "ET-国际".equals(taskInfo.getDataResourceType()) ? 0 : 1);

        return params;
    }

    @Override
    protected void doParseBefore(File file, Serializable fileId, Map<Object, Object> params) throws FileParseException {

        FileManagePO fileManagePO = get(params, TASK_FILEMANAGE_INFO);
        //设置AET是否是自动对接推送
        boolean autoFlag = AUTO_USERNAME.equals(fileManagePO.getUserName()) ? true : false;

        params.put(KEY_AUTO, autoFlag);

        if (!autoFlag) {
            //如果是手动解析需要对数据去重,因此在解析之前添加之前已入库数据
            QueryWrapper<TicketReconDataPO> wrapper = new QueryWrapper<>();
            wrapper.select("ticket_number", "coupon_ind", "associated_ticket_number", "transaction_code", "form_of_payment_type", "create_ticket_time", "domestic_indicate");
            wrapper.eq("file_manager_id", fileId);

            List<TicketReconDataPO> list = ticketReconDataService.list(wrapper);
            params.put(KEY_DATABASE_DATA, list);

        }
    }

    @Override
    protected File converFile(File file) throws FileParseException {
        //解压文件
        try {
            if (FileUtil.isZip(file)) {
                File parent = FileUtil.unZip(file, file.getParent());
                return parent.listFiles()[0];
            } else {
                return file;
            }
        } catch (ZipException e) {
            throw new FileParseException(StateEnum.STATE_ERROR_NOT_FOUND, e);
        }
    }

    @Override
    protected void doParseHeader(BufferedReader bufferedReader, int lines) throws DataFileException, IOException {
        String line = bufferedReader.readLine();
        if (StringUtils.isEmpty(line)) {
            throw new FileParseException(StateEnum.STATE_ERROR_CONTENT);
        } else if (line.length() >= 3) {
            if (!"TCN".equals(line.substring(0, 3))) {
                throw new FileParseException(StateEnum.STATE_ERROR_TEMPLATE);
            }
        }


    }

    @Override
    protected boolean isIgnoreLine(String line) {
        //如果数据为作废票则不录入数据，直接跳过当前循环
        boolean flag = "CANX".equals(line.substring(42, 46).trim());
        // 如果文件有空行就跳过
        flag = flag || line.length() < 2;
        return flag;
    }

    @Override
    protected boolean isIgnoreData(TicketReconDataPO data, Serializable fileId, Map<Object, Object> params) {
        //自动解析
        if (MapUtil.get(params, KEY_AUTO)) {
            return false;
        }

        //手动解析
        List<TicketReconDataPO> list = MapUtil.get(params, KEY_DATABASE_DATA);

        return list.contains(data);
    }

    @Override
    protected boolean isNewData(String line) {
        //01销售记录（每读取到一条01开头为一张新的客票）
        boolean flag = "01".equals(line.substring(0, 2));
        return flag;
    }

    @Override
    protected void updateDataByLine(TicketReconDataPO ticketrecon, String line, Serializable fileId, Map<Object, Object> params) {
        int flag = get(params, KEY_FLAG, 1);

        if (null == params.get(KEY_STINDEX)) {
            params.put(KEY_STINDEX, 200);
        }

        TMarketingRecord tmarketrecord;
        TAdditionalSalesDataRecord additionsaledata;
        TAllTaxesDetail talltaxes;
        TFinancialRecord tfinancialrecord;
        TFormOfPaymentRecord tpaymentrecord;
        TExchangedDocumentInformati texchangeInfo;

        if ("02".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_MR, 1);

            tmarketrecord = setTMarketingRecord(line);
            // 跳过入库基础表，提高性能 markketlist.add(tmarketrecord);
            // if(markketlist.size()/pointsDataLimit==1){
            // //tMarketingRecordMapper.insertTMarketingRecord((List<TMarketingRecord>)
            // EtTranUtil.TansListDatas(markketlist));
            // tMarketingRecordMapper.insertTMarketingRecord(markketlist);
            // markketlist.clear();
            //
            // }
        }
        if ("03".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_AS, 1);

            additionsaledata = (TAdditionalSalesDataRecord) EtTranUtil.TansListClassFieldTypes(
                    createAdditionalSalesDataRecord(line));
            // if(additionsaledata.getTaxType3().equals("XT")){
            // ticketrecon.setTx(additionsaledata.getTaxAmount3());//
            // (TX)其他税费
            // }else{
            // ticketrecon.setTx(0);// (TX)其他税费
            // }
            ticketrecon.setTotalTaxes(additionsaledata.getTotal());// 03的税费总计少了0.01
            // if(flag==0){
            // ticketrecon.setSettlementPrice(additionsaledata.getFare());//国际的结算价
            // }
            if (flag == 1) {
                if (!additionsaledata.getFareCurrency().isEmpty()) {
                    ticketrecon.setSettlementCurrency(additionsaledata.getFareCurrency());// 结算价币种
                } else {
                    ticketrecon.setSettlementCurrency("CNY");// 国内默认结算价币种为人民币
                }
            }
            // else if (flag==0){
            // ticketrecon.setSettlementCurrency(additionsaledata.getFareCurrency());//
            // 结算价币种
            // }
            // 国际退票结算价票价实退票价统一取票价，统一ecs的清洗规则
            if (flag == 0 && ticketrecon.getTransactionCode().equals("RFND")) {
                ticketrecon.setFareAmount(additionsaledata.getFare());
                ticketrecon.setSettlementPrice(additionsaledata.getFare());
//                double totalFareTax = additionsaledata.getTotalFareTax();
                // ticketrecon.setCollectedFare(additionsaledata.getFare());
                if (additionsaledata.getFare() != 0.00) {
                    ticketrecon.setCollectedFare(additionsaledata.getFare());
                }
            }


            String originalIssueInformation = additionsaledata.getOriginalIssueInformation();
            if (!originalIssueInformation.isEmpty() && originalIssueInformation.length() >= 13) {
                ticketrecon.setOriginalTicketNumber(additionsaledata.getOriginalIssueInformation().substring(0, 13));// 原票号
            } else {
                // 原票号
                ticketrecon.setOriginalTicketNumber("");
            }
        }
        if ("04".equals(line.substring(0, 2))) {
            for (int c = 0; c < 9; c++) {
                if (c > 0) {
                    mapValueAdd(params, KEY_STINDEX, 19);
                }
                mapValueAdd(params, KEY_COUNT_AT, 1);
                talltaxes = setTAllTaxesDetail(line, get(params, KEY_STINDEX));

                if (talltaxes.getTaxType().equals("OB")) {
                    ticketrecon.setOb(talltaxes.getTaxAmount());
                }
                if (talltaxes.getTaxType().equals("CN")) {
                    ticketrecon.setCn(ticketrecon.getCn() + talltaxes.getTaxAmount());
                }
                if (talltaxes.getTaxType().equals("YQ")) {
                    ticketrecon.setYq(ticketrecon.getYq() + talltaxes.getTaxAmount());
                }
                // if(talltaxes.getTaxType().equals("TX")){
                // ticketrecon.setTx(talltaxes.getTaxAmount());
                // }
                if (talltaxes.getTaxType().equals("YR")) {
                    ticketrecon.setYr(ticketrecon.getYr() + talltaxes.getTaxAmount());
                }
                if (talltaxes.getTaxType().equals("CP")) {
                    ticketrecon.setCp(talltaxes.getTaxAmount());
                }
                if (!talltaxes.getTaxType().equals("CP") && !talltaxes.getTaxType().equals("OB")
                        && !talltaxes.getTaxType().equals("GV")) {
                    // 退票费、变更费、汇款金额都不累加到总税费
                    mapValueAdd(params, KEY_SUM_ALL_TAX, talltaxes.getTaxAmount());
                }
            }
            params.put(KEY_STINDEX, 200);
            mapValueAdd(params, KEY_COUNT_TFR, 1);
            tfinancialrecord = (TFinancialRecord) EtTranUtil.TansListClassFieldTypes(setTFianacialRecord(line));

            if (flag == 0 && ticketrecon.getTransactionCode().equals("RFND")) {// 国际退票应收账款，统一ecs的清洗规则
                if (ticketrecon.getTotalAmount() == 0) {// 两条04的情况下，国际退票应收账款存放在第一条04
                    ticketrecon.setTotalAmount(tfinancialrecord.getTicketDocumentAmount());
                }
                // ticketrecon.setTotalAmount(tfinancialrecord.getTicketDocumentAmount());
                if (!tfinancialrecord.getCurrencyOfEquivalentFarePa().isEmpty()) {
                    ticketrecon.setSettlementCurrency(
                            tfinancialrecord.getCurrencyOfEquivalentFarePa().substring(0, 3));// 国际结算价币种
                } else {
                    ticketrecon.setSettlementCurrency(
                            tfinancialrecord.getCurrencyFare().substring(0, 3));// 国际结算价币种
                }
                ticketrecon.setFareCurrency(tfinancialrecord.getCurrencyFare());// 币种
                ticketrecon.setBasicFee(tfinancialrecord.getCommissionAmount1());// 基本费
                ticketrecon.setXFee(tfinancialrecord.getCommissionAmount2());// X费
                ticketrecon.setTx(ticketrecon.getTotalTaxes() - ticketrecon.getCn()
                        - ticketrecon.getYq() - ticketrecon.getYr());// 其他税计算，税总和-CN-YQ-YR
            } else {
                if (tfinancialrecord.getTicketDocumentAmount() != 0) {
                    ticketrecon.setCollectedFare(tfinancialrecord.getTicketDocumentAmount());
                }
                if (tfinancialrecord.getFareAmount() != 0) {
                    ticketrecon.setFareAmount(tfinancialrecord.getFareAmount());
                }
                // ticketrecon.setCollectedFare(tfinancialrecord.getTicketDocumentAmount());//实收价/实退票价/EMD实收价
                // ticketrecon.setFareAmount(tfinancialrecord.getFareAmount());//支付价/调账金额/票价总计
                ticketrecon.setBasicFee(tfinancialrecord.getCommissionAmount1());// 基本费
                ticketrecon.setXFee(tfinancialrecord.getCommissionAmount2());// X费
                // ticketrecon.setBasicFee(0);//基本费
                // ticketrecon.setXFee(0);//X费
                // 其他税计算，税总和-CN-YQ-YR
                double tx = ticketrecon.getTotalTaxes() - ticketrecon.getCn() - ticketrecon.getYq() - ticketrecon.getYr();
                ticketrecon.setTx(tx);
                if (flag == 1) {
                    ticketrecon.setSettlementPrice(tfinancialrecord.getFareAmount());// 国内的结算价=票价总计
                    if (!tfinancialrecord.getCurrencyFare().isEmpty()) {
                        ticketrecon.setFareCurrency(tfinancialrecord.getCurrencyFare());// 币种
                    } else {
                        ticketrecon.setFareCurrency("CNY");// 国内币种默认为人民币
                    }
                    ticketrecon.setTotalAmount(tfinancialrecord.getTicketDocumentAmount()
                            - ticketrecon.getBasicFee() - ticketrecon.getXFee());
                } else if (flag == 0) {
                    // if
                    // (!tfinancialrecord.getCurrencyOfEquivalentFarePa().isEmpty()){
                    // if
                    // (ticketrecon.getSettlementPrice()!=0.00){//有两条04的时候第二条为0，不能去第二条的值
                    // ticketrecon.setSettlementPrice(tfinancialrecord.getEquivalentFarePaid());
                    // }
                    // } else {
                    // if
                    // (ticketrecon.getSettlementPrice()!=0.00){//有两条04的时候第二条为0，不能去第二条的值
                    // ticketrecon.setSettlementPrice(ticketrecon.getCollectedFare()-ticketrecon.getTotalTaxes());//国际的结算价
                    // }
                    // }
                    // if
                    // (ticketrecon.getSettlementPrice()==0.00){//有两条04的时候第二条为0，不能去第二条的值
                    // ticketrecon.setSettlementPrice(ticketrecon.getCollectedFare()-ticketrecon.getTotalTaxes());//国际的结算价
                    // }
                    if (!tfinancialrecord.getCurrencyOfEquivalentFarePa().isEmpty()) {
                        ticketrecon.setSettlementCurrency(
                                tfinancialrecord.getCurrencyOfEquivalentFarePa().substring(0, 3));// 国际结算价币种
                    } else {
                        ticketrecon.setSettlementCurrency(
                                tfinancialrecord.getCurrencyFare().substring(0, 3));// 国际结算价币种
                    }

                    ticketrecon.setFareCurrency(tfinancialrecord.getCurrencyFare());// 币种
                    ticketrecon.setTotalAmount(ticketrecon.getCollectedFare());// 应收账款
                }
            }
        }
        if ("05".equals(line.substring(0, 2))) {

            mapValueAdd(params, KEY_COUNT_IR, 1);

            Integer number = ticketrecon.getConjunctionTotalTickets();
            // 长度获取
            line = line.trim();
            int len = line.length();
            String disabledSoldiersIdType = "";
            switch (number) {
                case 1:
                    // 当前长度必须大于109+15才可以进行截取
                    if (len > 109 + 15) {
                        disabledSoldiersIdType = line.substring(109, 109 + 15);
                    }
                    break;
                case 2:
                    // 当前长度必须大于198+15才可以进行截取
                    if (len > 198 + 15) {
                        disabledSoldiersIdType = line.substring(198, 198 + 15);
                    }
                    break;
                case 3:
                    // 当前长度必须大于287+15才可以进行截取
                    if (len > 287 + 15) {
                        disabledSoldiersIdType = line.substring(287, 287 + 15);
                    }
                    break;
                case 4:
                    // 当前长度必须大于376+15才可以进行截取
                    if (len > 376 + 15) {
                        disabledSoldiersIdType = line.substring(376, 376 + 15);
                    }
                    break;
                default:
                    break;
            }

            if (StringUtils.isNotEmpty(disabledSoldiersIdType)) {
                if (disabledSoldiersIdType.contains("jc") || disabledSoldiersIdType.contains("JC")) {
                    disabledSoldiersIdType = "0";
                } else if (disabledSoldiersIdType.contains("gm") || disabledSoldiersIdType.contains("GM")) {
                    disabledSoldiersIdType = "1";
                } else {
                    disabledSoldiersIdType = "";
                }
                ticketrecon.setDisabledsoldiersidtype(disabledSoldiersIdType);
            }
        }

        if ("07".equals(line.substring(0, 2))) {

            mapValueAdd(params, KEY_COUNT_PR, 1);


            tpaymentrecord = (TFormOfPaymentRecord) EtTranUtil.TansListClassFieldTypes(setTFormOfPaymentRecord(line));
            // 跳过入库基础表，提高性能 paymentlist.add(tpaymentrecord);
            ticketrecon.setFormOfPaymentType(tpaymentrecord.getFormOfPaymentType());
            // 国际变更票的票价取差价(交易总金额),结算价也取差价(交易总金额),对应Ecs的清洗规则。
            if (flag == 0 && ticketrecon.getFormOfPaymentType().equals("EX")) {
                ticketrecon.setFareAmount(ticketrecon.getCollectedFare());
                ticketrecon.setSettlementPrice(ticketrecon.getCollectedFare());
                // 国际换开变更不对账
                ticketrecon.setCheckedSellData(-1);
            }
            // 跳过入库基础表，提高性能
            // if(paymentlist.size()/pointsDataLimit==1){
            // //tFormOfPaymentRecordMapper.insertTFormOfPaymentRecord((List<TFormOfPaymentRecord>)
            // EtTranUtil.TansListDatas(paymentlist));
            // tFormOfPaymentRecordMapper.insertTFormOfPaymentRecord(paymentlist);
            // paymentlist.clear();
            // }
        }
        if ("08".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_FC, 1);
            // 跳过入库基础表，提高性能
            // farecalculationlist.add(TFareCalculationRecordUtil.setTFareCalculationRecord(lineTxt));
            // if(farecalculationlist.size()/pointsDataLimit==1){
            // //tFareCalculationRecordMapper.insertTFareCalculationRecord((List<TFareCalculationRecord>)
            // EtTranUtil.TansListDatas(farecalculationlist));
            // tFareCalculationRecordMapper.insertTFareCalculationRecord(farecalculationlist);
            // farecalculationlist.clear();
            // }
        }
        if ("09".equals(line.substring(0, 2))) {

            mapValueAdd(params, KEY_COUNT_ED, 1);

            texchangeInfo = (TExchangedDocumentInformati) EtTranUtil.TansListClassFieldTypes(
                    setTExchangedDocumentInformati(line));
            // 跳过入库基础表，提高性能 exchangelist.add(texchangeInfo);
            //// ticketrecon.setOriginalTicketNumber(texchangeInfo.getTicket1OriginalTicketNumber());
            // if(exchangelist.size()/pointsDataLimit==1){
            // //tExchangedDocumentInformatiMapper.insertTExchangedDocumentInformati((List<TExchangedDocumentInformati>)
            // EtTranUtil.TansListDatas(exchangelist));
            // tExchangedDocumentInformatiMapper.insertTExchangedDocumentInformati(exchangelist);
            // exchangelist.clear();
            // }
        }
        if ("11".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_AI, 1);

            // 跳过入库基础表，提高性能
            // aircraftinfolist.add(TAircraftInfoUtil.setTAircraftInformation(lineTxt));
            // if(aircraftinfolist.size()/pointsDataLimit==1){
            // //tAircraftInformationMapper.insertTAircraftInformation((List<TAircraftInformation>)
            // EtTranUtil.TansListDatas(aircraftinfolist));
            // tAircraftInformationMapper.insertTAircraftInformation(aircraftinfolist);
            // aircraftinfolist.clear();
            // }
        }

        if ("15".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_EC, 1);
            // 跳过入库基础表，提高性能
            // emdcouponlist.add(TEmdCouponDetailUtil.setTEmdCouponDetail(lineTxt));
            // if(emdcouponlist.size()/pointsDataLimit==1){
            // //tEmdCouponDetailMapper.insertTEmdCouponDetail((List<TEmdCouponDetail>)
            // EtTranUtil.TansListDatas(emdcouponlist));
            // tEmdCouponDetailMapper.insertTEmdCouponDetail(emdcouponlist);
            // emdcouponlist.clear();
            // }
        }
        if ("16".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_ER, 1);
            // 跳过入库基础表，提高性能
            // remarkbaglist.add(TEmdRemarkBaggageUtil.setTEmdRemarksBaggage(lineTxt));
            // if(remarkbaglist.size()/pointsDataLimit==1){
            // //tEmdRemarksBaggageMapper.insertTEmdRemarksBaggage((List<TEmdRemarksBaggage>)
            // EtTranUtil.TansListDatas(remarkbaglist));
            // tEmdRemarksBaggageMapper.insertTEmdRemarksBaggage(remarkbaglist);
            // remarkbaglist.clear();
            // }
        }

        if ("17".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_ES, 1);
            // 跳过入库基础表，提高性能
            // emdservicelist.add(TEmdServiceDesUtil.setTEmdServiceDes(lineTxt));
            // if(emdservicelist.size()/pointsDataLimit==1){
            // //tEmdServiceDesMapper.insertTEmdServiceDes((List<TEmdServiceDes>)
            // EtTranUtil.TansListDatas(emdservicelist));
            // tEmdServiceDesMapper.insertTEmdServiceDes(emdservicelist);
            // emdservicelist.clear();
            // }
        }

        if ("98".equals(line.substring(0, 2))) {
            mapValueAdd(params, KEY_COUNT_AF, 1);
            // 跳过入库基础表，提高性能
            // addinfolist.add(TAdditionInformationUtil.setTAdditionInformation(lineTxt));
            // if(addinfolist.size()/pointsDataLimit==1){
            // //tAdditionInformationMapper.insertTAdditionInformation((List<TAdditionInformation>)
            // EtTranUtil.TansListDatas(addinfolist));
            // tAdditionInformationMapper.insertTAdditionInformation(addinfolist);
            // addinfolist.clear();
            // }
        }
    }

    @Override
    protected void updateDataLast(TicketReconDataPO ticketrecon, String line, Serializable fileId, Map<Object, Object> params) {
        //国内国际标记
        int flag = get(params, KEY_FLAG, 1);

        if (ticketrecon.getTransactionCode() != null && ticketrecon.getFormOfPaymentType() != null) {
            if (flag == 0) {

                double sumAllTax = get(params, KEY_SUM_ALL_TAX);
                // 04的所有税费总计
                ticketrecon.setTotalTaxes(sumAllTax);
                // 其他税计算，税总和-CN-YQ-YR
                double tx = ticketrecon.getTotalTaxes() - ticketrecon.getCn() - ticketrecon.getYq() - ticketrecon.getYr();
                ticketrecon.setTx(tx);

                if (!ticketrecon.getFormOfPaymentType().equals("EX")) {
                    if (ticketrecon.getCollectedFare() == 0) {
                        double totalFareTax = get(params, KEY_TOTAL_FARE_TAX, 0.0);
                        ticketrecon.setCollectedFare(totalFareTax - ticketrecon.getTotalTaxes());
                    }
                    // 如果实退价取值为0，通过计算获得
                    if (!ticketrecon.getTransactionCode().equals("RFND")) {
                        // 国际非退票的结算价
                        ticketrecon.setSettlementPrice(ticketrecon.getCollectedFare() - ticketrecon.getTotalTaxes());
                    }
                }
            }
            if (ticketrecon.getTransactionCode().equals("EMDS")
                    || ticketrecon.getTransactionCode().equals("EMDA")) {
                // EMD票票面价为0
                ticketrecon.setFareAmount(DOUBLE_ZERO);
                // ticketrecon.setFareCurrency("");
            }
        }


        // 联票的第二张票清洗后对账表的值都设为0，对应ECS的清洗规则
        boolean flag1 = (flag == 0 && ticketrecon.getConjunctionTicketIndicator().equals("CNJ"));
        // 国内除了退票的联票的第二张票清洗后对账表的值都设为0，对应ECS的清洗规则
        boolean flag2 = (flag == 1 && ticketrecon.getConjunctionTicketIndicator().equals("CNJ")
                && !ticketrecon.getTransactionCode().equals("RFND"));

        if (flag1 || flag2) {
            ticketrecon.setSettlementPrice(DOUBLE_ZERO);
            // ticketrecon.setSettlementCurrency("");
            ticketrecon.setFareAmount(DOUBLE_ZERO);
            // ticketrecon.setFareCurrency("");
            ticketrecon.setCollectedFare(DOUBLE_ZERO);
            ticketrecon.setTotalAmount(DOUBLE_ZERO);
            ticketrecon.setTotalTaxes(DOUBLE_ZERO);
            ticketrecon.setBasicFee(DOUBLE_ZERO);
            ticketrecon.setXFee(DOUBLE_ZERO);
            ticketrecon.setTx(DOUBLE_ZERO);
            ticketrecon.setOb(DOUBLE_ZERO);
            ticketrecon.setCn(DOUBLE_ZERO);
            ticketrecon.setYq(DOUBLE_ZERO);
            ticketrecon.setYr(DOUBLE_ZERO);
            ticketrecon.setCp(DOUBLE_ZERO);
        }

        if (EtPaymentTypeEnum.Chartered.getValue().equals(ticketrecon.getFormOfPaymentType())) {
            ticketrecon.setSettlementCurrency("MIL");
        }
    }

    /**
     * 创建票数据对象
     *
     * @param line   把行字符串转换为数据对象
     * @param fileId
     * @param params
     * @return
     * @throws FileParseException
     */
    @Override
    public TicketReconDataPO parseLineToData(String line, Serializable fileId, Map<Object, Object> params) throws FileParseException {
        int flag = get(params, KEY_FLAG, 1);

        TicketReconDataPO ticketrecon = new TicketReconDataPO();
        // 设置文件ID
        ticketrecon.setFileManagerId((Long) fileId);

        TicketSale ticketsale = (TicketSale) EtTranUtil.TansListClassFieldTypes(createTicketSale(line, flag));

        ticketrecon.setTicketNumber(ticketsale.getTicketNumber());
        // 联票标识符
        ticketrecon.setConjunctionTicketIndicator(ticketsale.getConjunctionTicketIndicator());
        // 联票中的第一张票
        ticketrecon.setConjunctionPrimeTicket(ticketsale.getConjunctionPrimeTicket());

        // 联票序号
        ticketrecon.setConjunctionRelativeTicket(Integer.parseInt(EtTranUtil.setDefaultvale(ticketsale.getConjunctionRelativeTicket())));
        // 总票数
        ticketrecon.setConjunctionTotalTickets(Integer.parseInt(EtTranUtil.setDefaultvale(ticketsale.getConjunctionTotalTickets())));
        // 航段标识符
        ticketrecon.setCouponInd(ticketsale.getCouponInd());
        // 关联票号
        ticketrecon.setAssociatedTicketNumber(ticketsale.getAssociatedTicketNumber());
        // 交易类型
        ticketrecon.setTransactionCode(ticketsale.getTransactionCode());
        // ticketrecon.setCreateTicketTime(ticketsale.getCreateTime());

        // 出票日期
        String createTicketTime = ticketsale.getCreateTime().substring(0, 4) + "-"
                + ticketsale.getCreateTime().substring(4, 6) + "-"
                + ticketsale.getCreateTime().substring(6, 8) + " 00:00:00";

        ticketrecon.setCreateTicketTime(createTicketTime);

        ticketrecon.setDomesticIndicate(flag);
        ticketrecon.setCreationTime(ticketsale.getImpDate());
        // 跳过入库基础表，提高性能 ticketlist.add(ticketsale);
        // 清洗退单号和退款单号逻辑
        if (!ticketrecon.getAssociatedTicketNumber().isEmpty()) {
            // 清洗前缀'784'
            String refundNo = ticketrecon.getAssociatedTicketNumber().substring(3);
            // ticketrecon.setRefundno(ticketrecon.getAssociatedTicketNumber().substring(3));
            if (flag == 0) {
                // 结算国际 T8011611123==>T1801160011123

                StringBuilder sb = new StringBuilder(refundNo);
                sb.insert(1, "1").insert(7, "00");
                refundNo = sb.toString();
            }
            ticketrecon.setRefundno(refundNo);
        }

        mapValueAdd(params, KEY_COUNT_TS, 1);
        return ticketrecon;
    }

    @Override
    protected void doParseAfter(DispatchLogPO dispatchLog, ParseResult parseResult, File file, Serializable fileId, Map<Object, Object> params) throws DataFileException {
        super.doParseAfter(dispatchLog, parseResult, file, fileId, params);

    }

    @Override
    public boolean insertData(List<TicketReconDataPO> datas, Serializable fileId) throws DataOperaterException {
        try {
            return ticketReconDataService.saveBatch(datas) > 0;
        } catch (Exception e) {
            throw new DataOperaterException("fileId=" + fileId + "数据入库异常", e);
        }
    }

    /**
     * @param path
     * @param fileName
     * @param dispatchLog
     * @param params
     * @return
     * @throws DataFileException
     */
    @Override
    protected FileManagePO getFileManage(String path, String fileName, DispatchLogPO dispatchLog, Map<Object, Object> params) throws DataFileException {
        FileManagePO fileManage = super.getFileManage(path, fileName, dispatchLog, params);

        if (fileManage == null) {
            FileBaseinfoPO taskInfo = get(params, TASK_BASE_INFO);
            fileManage = new FileManagePO();
            fileManage.setCreateTime(new Date());
            fileManage.setFileName(fileName);
            fileManage.setDataDetail(fileName);
            fileManage.setFileSources(taskInfo.getId());
            fileManage.setLink(path);
            fileManage.setUserName(AUTO_USERNAME);
            fileManage.setFileUploadDate(dispatchLog.getDispatchDate());
        }
        return fileManage;
    }

    /**
     * ET-国内：181031aet.zip
     * ET-国际：CZTCN181031.txt
     *
     * @param dispatchLog
     * @param params
     * @return
     */
    @Override
    public String generateFileName(DispatchLogPO dispatchLog, Map<Object, Object> params) {
        FileBaseinfoPO taskInfo = get(params, TASK_BASE_INFO);
        String formatDate = DateFormatUtils.format(dispatchLog.getDispatchDate(), "yyMMdd");

        if ("ET-国际".equals(taskInfo.getDataResourceType())) {
            return "CZTCN" + formatDate + ".txt";
        }
        return formatDate + "aet.zip";
    }

    @Override
    protected boolean clearDataByFileId(Serializable fileId) throws DataFileException {
        return ticketReconDataService.clearDataByFileId("file_manager_id", (Long) fileId);
    }

    /**
     * 传教票销售
     *
     * @param line
     * @param flag
     * @return
     */
    TicketSale createTicketSale(String line, int flag) {
        TicketSale ticketsale = new TicketSale();

        ticketsale.setImpDate(new Date());

        ticketsale.setTicketNumber(Long.parseLong(line.substring(10, 25).trim()));

        ticketsale.setTicketModeInd(subStrTrimDef(line, 50, 51));

        ticketsale.setConjunctionTicketIndicator(subStrTrimDef(line, 51, 54));

        ticketsale.setConjunctionRelativeTicket(subStrTrimDef(line, 54, 56));

        //联票中的第一张票
        ticketsale.setConjunctionPrimeTicket(subStrTrimDef(line, 58, 68));

        //联票总票数
        ticketsale.setConjunctionTotalTickets(subStrTrimDef(line, 56, 58));

        ticketsale.setCouponInd(subStrTrimDef(line, 68, 72));

        //关联票号
        ticketsale.setAssociatedTicketNumber(subStrTrimDef(line, 72, 87));

        //交易类型
        ticketsale.setTransactionCode(subStrTrimDef(line, 42, 46));

        ticketsale.setCreateTime(subStrTrimDef(line, 156, 164));

        //报告系统标识
        ticketsale.setReportingSystem(subStrTrimDef(line, 87, 91));

        //PNR标识符
        ticketsale.setPnrRefAirlineData(subStrTrimDef(line, 91, 104));

        //重运承运人
        try {
            String retransmissionCarrier = new String(new String(line.substring(104, 107).getBytes("ISO-8859-1"), "GBK").getBytes(), "UTF-8").trim();
            ticketsale.setRetransmissionCarrier(retransmissionCarrier);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //旅客姓名拼音
        try {
            ticketsale.setPassengerName(new String(new String(line.substring(107, 156).getBytes("ISO-8859-1"), "GBK").getBytes(), "ISO-8859-1").trim().toString());
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //出票点标识符
        ticketsale.setTicketingEntityOutletType(subStrTrimDef(line, 164, 165));

        //出票代理人
        ticketsale.setAgentNumericCode(subStrTrimDef(line, 165, 173));

        //有效的代理人协议号
        ticketsale.setValidatingAgencyNumericCode(subStrTrimDef(line, 173, 181));

        //客户身份证
        ticketsale.setClientIdentification(subStrTrimDef(line, 181, 196));

        //预定标识符
        ticketsale.setBookingEntityOutletType(subStrTrimDef(line, 196, 197));

        ticketsale.setBookingAgencyLocationNumber(subStrTrimDef(line, 197, 205));

        ticketsale.setBookingLocationIsoCountryC(subStrTrimDef(line, 205, 207));

        ticketsale.setPointOfSale(subStrTrimDef(line, 207, 212));

        ticketsale.setPointOfTicketIssuance(subStrTrimDef(line, 212, 217));

        ticketsale.setTicketingEntityIsoCountryC(subStrTrimDef(line, 217, 219));

        ticketsale.setBookingAgentIdentification(subStrTrimDef(line, 332, 339));

        ticketsale.setInternationalSaleIndicator(subStrTrimDef(line, 339, 343));

        ticketsale.setStatisticalCode(subStrTrimDef(line, 343, 346));

        ticketsale.setRoundTripIndicator(subStrTrimDef(line, 346, 347));

        ticketsale.setPriceIndicator(subStrTrimDef(line, 347, 348));

        ticketsale.setElectronicTicketIndicator(subStrTrimDef(line, 348, 350));

        ticketsale.setNoticeInd(subStrTrimDef(line, 350, 351));

        ticketsale.setSupportDocumentInd(subStrTrimDef(line, 351, 353));

        ticketsale.setDataSourceCode(subStrTrimDef(line, 353, 357));

        ticketsale.setVoluntaryInvoluntaryCode(subStrTrimDef(line, 357, 358));

        ticketsale.setSettlementAuthorizationCode(subStrTrimDef(line, 358, 372));

        ticketsale.setAtpcoCodeshareIndicator(subStrTrimDef(line, 372, 373));

        ticketsale.setDomesticIndicate(flag);

        return ticketsale;
    }

    TMarketingRecord setTMarketingRecord(String lineTxt) {
        TMarketingRecord tmarketrecord = new TMarketingRecord();
        tmarketrecord.setImpDate(new Date());

        tmarketrecord.settId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        tmarketrecord.setPseudoCityCode(lineTxt.substring(42, 48).trim());

        if (lineTxt.substring(48, 49).trim().equals("0")) {//如果时间是00000000,设置默认时间1970-01-01
            tmarketrecord.setDateOfPnrCreation("1970-01-01 00:00:00");
        } else {
            tmarketrecord.setDateOfPnrCreation(lineTxt.substring(48, 52).trim() + "-" + lineTxt.substring(52, 54).trim() + "-" + lineTxt.substring(54, 56).trim() + " 0000:00:00");
        }


        tmarketrecord.setInternetIpNumber(subStrTrimDef(lineTxt, 56, 86));
        tmarketrecord.setTelephoneNumber(lineTxt.substring(86, 106).trim());
        tmarketrecord.setSponsorInformation(lineTxt.substring(106, 140).trim());
        tmarketrecord.setAirlineConfirmationNumber(lineTxt.substring(140, 160).trim());
        tmarketrecord.setTicketWaiverCode(lineTxt.substring(160, 166).trim());
        tmarketrecord.setTimeOfTicketingIssue(lineTxt.substring(166, 170).trim());
        tmarketrecord.setBookingTime(lineTxt.substring(170, 174).trim());
        tmarketrecord.setCoupon1SegmentBookingDate(lineTxt.substring(174, 179).trim());
        tmarketrecord.setCoupon1AirlinePnrReference(lineTxt.substring(179, 192).trim());
        tmarketrecord.setCoupon1FrequentFlyerNumber(lineTxt.substring(192, 208).trim());
        tmarketrecord.setCoupon1WaiverCode(lineTxt.substring(208, 214).trim());
        tmarketrecord.setCoupon2SegmentBookingDate(lineTxt.substring(214, 219).trim());
        tmarketrecord.setCoupon2AirlinePnrReference(lineTxt.substring(219, 232).trim());
        tmarketrecord.setCoupon2FrequentFlyerNumber(lineTxt.substring(232, 248).trim());
        tmarketrecord.setCoupon2WaiverCode(lineTxt.substring(248, 254).trim());
        tmarketrecord.setCoupon3SegmentBookingDate(lineTxt.substring(254, 259).trim());
        tmarketrecord.setCoupon3AirlinePnrReference(lineTxt.substring(259, 272).trim());
        tmarketrecord.setCoupon3FrequentFlyerNumber(lineTxt.substring(272, 288).trim());
        tmarketrecord.setCoupon3WaiverCode(lineTxt.substring(288, 294).trim());
        tmarketrecord.setCoupon4SegmentBookingDate(lineTxt.substring(294, 299).trim());
        tmarketrecord.setCoupon4AirlinePnrReference(lineTxt.substring(299, 312).trim());
        tmarketrecord.setCoupon4FrequentFlyerNumber(lineTxt.substring(312, 328).trim());
        tmarketrecord.setCoupon4WaiverCode(lineTxt.substring(328, 334).trim());

        return tmarketrecord;
    }

    TAdditionalSalesDataRecord createAdditionalSalesDataRecord(String lineTxt) {
        TAdditionalSalesDataRecord addsalesrecord = new TAdditionalSalesDataRecord();
        addsalesrecord.setImpDate(new Date());
        addsalesrecord.settId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        addsalesrecord.setOriginAirportCityCode(lineTxt.substring(42, 47).trim());// 始发城市代码
        addsalesrecord.setDestinationAirportCityCode(lineTxt.substring(47, 52).trim());// 到达城市代码
        addsalesrecord.setTrueOriginDestinationCityC(lineTxt.substring(52, 66).trim());// 实际始发/到达
        addsalesrecord.setAllianceOriginDestinationCi(lineTxt.substring(66, 80).trim());// 联合始发/到达
        addsalesrecord.setAllianceCarveOutIndicator(lineTxt.substring(80, 81).trim());// 联合/分离标识符
        //cht:票价入库改用decimal
        if (lineTxt.substring(84, 92).trim().isEmpty()) {
            addsalesrecord.setFare(0);
        } else {
            addsalesrecord.setFare(Double.valueOf(lineTxt.substring(84, 92).trim()));// 票价
        }
//		addsalesrecord.setFare(lineTxt.substring(84, 92).trim());// 票价
        addsalesrecord.setFareCurrency(lineTxt.substring(81, 84).trim());// 币种
        addsalesrecord.setEquivalentFarePaid(lineTxt.substring(92, 103).trim());// 实付等值票价
        if (lineTxt.length() == 411) {
            addsalesrecord.setTaxType(lineTxt.substring(114, 116).trim());// 税类型
            //cht:税费入库改用decimal
//			addsalesrecord.setTaxAmount(lineTxt.substring(116, 125).trim());// 税费
            if (lineTxt.substring(116, 125).trim().isEmpty()) {
                addsalesrecord.setTaxAmount(0);
            } else {
                addsalesrecord.setTaxAmount(Double.valueOf(lineTxt.substring(116, 125).trim()));// 税费
            }
            addsalesrecord.setTaxType2(lineTxt.substring(125, 127).trim());
//			addsalesrecord.setTaxAmount2(lineTxt.substring(127, 136).trim());
            if (lineTxt.substring(127, 136).trim().isEmpty()) {
                addsalesrecord.setTaxAmount2(0);
            } else {
                addsalesrecord.setTaxAmount2(Double.valueOf(lineTxt.substring(127, 136).trim()));
            }
            addsalesrecord.setTaxType3(lineTxt.substring(136, 138).trim());
//			addsalesrecord.setTaxAmount3(lineTxt.substring(138, 147).trim());
            if (lineTxt.substring(138, 147).trim().isEmpty()) {
                addsalesrecord.setTaxAmount3(0);
            } else {
                addsalesrecord.setTaxAmount3(Double.valueOf(lineTxt.substring(138, 147).trim()));
            }
            addsalesrecord.setCurrency(lineTxt.substring(147, 150).trim());//
//			addsalesrecord.setTotal(lineTxt.substring(150, 158).trim());
            if (!addsalesrecord.getTaxType3().equals("OB")) {
                addsalesrecord.setTotal(addsalesrecord.getTaxAmount() + addsalesrecord.getTaxAmount2() + addsalesrecord.getTaxAmount3());
            }
            addsalesrecord.setTourCode(lineTxt.substring(158, 173).trim());
            addsalesrecord.setPassengerType(lineTxt.substring(173, 176).trim());
            addsalesrecord.setPassengerSpecificData(lineTxt.substring(176, 225).trim());
            addsalesrecord.setOriginalIssueInformation(lineTxt.substring(225, 257).trim());
            addsalesrecord.setEndorsementsRestrictions(null);
        } else if (lineTxt.length() == 394) {
//			addsalesrecord.setTaxType(lineTxt.substring(112, 114).trim());// 税类型
            addsalesrecord.setTaxType(lineTxt.substring(103, 105).trim());// 税类型
//			addsalesrecord.setTaxAmount(lineTxt.substring(105, 112).trim());// 税费
            if (lineTxt.substring(105, 112).trim().isEmpty()) {
                addsalesrecord.setTaxAmount(0);
            } else {
                addsalesrecord.setTaxAmount(Double.valueOf(lineTxt.substring(105, 112).trim()));// 税费
            }
//			addsalesrecord.setTaxType2(lineTxt.substring(121, 123).trim());
            addsalesrecord.setTaxType2(lineTxt.substring(112, 114).trim());
//			addsalesrecord.setTaxAmount2(lineTxt.substring(114, 121).trim());
            if (lineTxt.substring(114, 121).trim().isEmpty()) {
                addsalesrecord.setTaxAmount2(0);
            } else {
                addsalesrecord.setTaxAmount2(Double.valueOf(lineTxt.substring(114, 121).trim()));
            }
            addsalesrecord.setTaxType3(lineTxt.substring(121, 123).trim());
//			addsalesrecord.setTaxAmount3(lineTxt.substring(123, 130).trim());
            if (lineTxt.substring(123, 130).trim().isEmpty()) {
                addsalesrecord.setTaxAmount3(0);
            } else {
                addsalesrecord.setTaxAmount3(Double.valueOf(lineTxt.substring(123, 130).trim()));
            }
            addsalesrecord.setTotalFareTax(Double.valueOf(lineTxt.substring(130, 141).trim()) / 100);//票价和税总和
            addsalesrecord.setCurrency("CNY");//
//			addsalesrecord.setTotal(lineTxt.substring(130, 141).trim());
            addsalesrecord.setTotal(addsalesrecord.getTaxAmount() + addsalesrecord.getTaxAmount2() + addsalesrecord.getTaxAmount3());
            addsalesrecord.setTourCode(lineTxt.substring(141, 156).trim());
            addsalesrecord.setPassengerType("");
            addsalesrecord.setPassengerSpecificData("");
            addsalesrecord.setOriginalIssueInformation("");
            addsalesrecord.setEndorsementsRestrictions(null);
        } else {
            if ("PD".equals(lineTxt.substring(103, 105).trim())) { // PD代表已收
                addsalesrecord.setTaxType(lineTxt.substring(112, 114).trim());// 税类型
                addsalesrecord.setTaxAmount(0);// 税费
                addsalesrecord.setTaxType2(lineTxt.substring(123, 125).trim());
                addsalesrecord.setTaxAmount2(0);
                addsalesrecord.setTaxType3(lineTxt.substring(125, 127).trim());
//				addsalesrecord.setTaxAmount3(lineTxt.substring(127, 136).trim());
                if (lineTxt.substring(127, 136).trim().isEmpty()) {
                    addsalesrecord.setTaxAmount3(0);
                } else {
                    String str = lineTxt.substring(127, 136).trim();
                    if (str.contains("EXEMPT")) {
                        addsalesrecord.setTaxAmount3(0);
                    } else {
                        addsalesrecord.setTaxAmount3(Double.valueOf(EtTranUtil.removeStrLetter(str)));
                    }

                }
                addsalesrecord.setCurrency("CNY");//
//				if ("ADC".equals(lineTxt.substring(139, 147).trim())) {
//					addsalesrecord.setTotal("0.00");
//				} else {
//					addsalesrecord.setTotal(lineTxt.substring(139, 146).trim());
//				}
                addsalesrecord.setTotal(addsalesrecord.getTaxAmount() + addsalesrecord.getTaxAmount2() + addsalesrecord.getTaxAmount3());
            } else {
                addsalesrecord.setTaxType(lineTxt.substring(103, 105).trim());// 税类型
//				addsalesrecord.setTaxAmount(lineTxt.substring(105, 114).trim());// 税费
                if (lineTxt.substring(105, 114).trim().isEmpty()) {
                    addsalesrecord.setTaxAmount(0);
                } else {
                    String str = lineTxt.substring(105, 114).trim();
                    //没有税费
                    if (str.contains("EXEMPT")) {
                        addsalesrecord.setTaxAmount(0);
                    } else {
                        addsalesrecord.setTaxAmount(Double.valueOf(str));// 税费
                    }

                }
                addsalesrecord.setTaxType2(lineTxt.substring(114, 116).trim());
//				addsalesrecord.setTaxAmount2(lineTxt.substring(116, 125).trim());
                if (lineTxt.substring(116, 125).trim().isEmpty()) {
                    addsalesrecord.setTaxAmount2(0);
                } else {
                    String str = lineTxt.substring(116, 125).trim();
                    if (str.contains("EXEMPT")) {
                        addsalesrecord.setTaxAmount2(0);
                    } else {
                        addsalesrecord.setTaxAmount2(Double.valueOf(EtTranUtil.removeStrLetter(str)));
                    }

                }
                addsalesrecord.setTaxType3(lineTxt.substring(125, 127).trim());
//				addsalesrecord.setTaxAmount3(lineTxt.substring(127, 136).trim());
                if (lineTxt.substring(127, 136).trim().isEmpty()) {
                    addsalesrecord.setTaxAmount3(0);
                } else {
                    String str = lineTxt.substring(127, 136).trim();
                    if (str.contains("EXEMPT")) {
                        addsalesrecord.setTaxAmount3(0);
                    } else {
                        addsalesrecord.setTaxAmount3(Double.valueOf(EtTranUtil.removeStrLetter(str)));
                    }

                }
                addsalesrecord.setCurrency(lineTxt.substring(136, 139).trim());//
//				addsalesrecord.setTotal(lineTxt.substring(139, 147).trim());
                addsalesrecord.setTotal(addsalesrecord.getTaxAmount() + addsalesrecord.getTaxAmount2() + addsalesrecord.getTaxAmount3());
            }
            addsalesrecord.setTourCode(lineTxt.substring(147, 162).trim());
            addsalesrecord.setPassengerType(lineTxt.substring(162, 165).trim());
            addsalesrecord.setPassengerSpecificData(lineTxt.substring(165, 214).trim());
            addsalesrecord.setOriginalIssueInformation(lineTxt.substring(214, 246).trim());
//			addsalesrecord.setEndorsementsRestrictions(lineTxt.substring(246, 393).trim());
        }
        return addsalesrecord;
    }

    TAllTaxesDetail setTAllTaxesDetail(String lineTxt, int stindex) {
        TAllTaxesDetail talltaxes = new TAllTaxesDetail();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(sdf.format(new Date()));
            talltaxes.setImpDate(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        talltaxes.setTId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        if (lineTxt.substring(stindex, stindex + 8).trim().isEmpty()) {
            talltaxes.setTaxType("");
        } else {
            talltaxes.setTaxType(lineTxt.substring(stindex, stindex + 8).trim());
        }
        String tasamountval = lineTxt.substring(stindex + 8, stindex + 19).trim();
        tasamountval = tasamountval.replaceAll("}", "");
        String reamountval;
        if (tasamountval.isEmpty()) {
            talltaxes.setTaxAmount(0);
        } else if (tasamountval.indexOf("-") != -1) {
            reamountval = tasamountval.replaceAll("-", "0");
            talltaxes.setTaxAmount(-Double.parseDouble(reamountval) / 100);
        } else {
            talltaxes.setTaxAmount(Double.parseDouble(tasamountval) / 100);
        }
//				talltaxes.setTaxType(lineTxt.substring(200,208).trim());
//				talltaxes.setTaxAmount(Double.valueOf(lineTxt.substring(208,219).trim()));
        return talltaxes;
    }

    TFinancialRecord setTFianacialRecord(String lineTxt) {
        TFinancialRecord tfinancialrecord = new TFinancialRecord();
//				tfinancialrecord.setID( DateUtil.getDataTimeSeq(count));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(sdf.format(new Date()));
            tfinancialrecord.setImpDate(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        tfinancialrecord.settId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        tfinancialrecord.setTicketDocumentAmount(CalculateUtil.cal(lineTxt.substring(42, 53).trim().replace("}", "0")));
        tfinancialrecord.setFareAmount(CalculateUtil.cal(lineTxt.substring(53, 64).trim()));
        tfinancialrecord.setCurrencyFare(lineTxt.substring(64, 68).trim());
        tfinancialrecord.setEquivalentFarePaid(CalculateUtil.cal(lineTxt.substring(68, 79).trim()));

        tfinancialrecord.setCurrencyOfEquivalentFarePa(lineTxt.substring(79, 83).trim());
        if (lineTxt.substring(149, 154).trim().isEmpty()) {
            tfinancialrecord.setEffectiveCommissionRate(0);
        } else {
            tfinancialrecord.setEffectiveCommissionRate(Double.valueOf(lineTxt.substring(149, 154).trim()));
        }
        tfinancialrecord.setEffectiveCommissionAmount(CalculateUtil.cal(lineTxt.substring(154, 165).trim()));
        tfinancialrecord.setAmountEnteredByAgent(CalculateUtil.cal(lineTxt.substring(167, 178).trim()));
        tfinancialrecord.setAmountPaidByCustomer(CalculateUtil.cal(lineTxt.substring(178, 189).trim()));
        tfinancialrecord.setExchangedTicketTotalSaleAm(CalculateUtil.cal(lineTxt.substring(189, 200).trim()));
        tfinancialrecord.setTaxOnCommission(lineTxt.substring(371, 372).trim());
        tfinancialrecord.setCommissionType1(lineTxt.substring(83, 89).trim());
        if (lineTxt.substring(89, 94).trim().isEmpty()) {
            tfinancialrecord.setCommissionRate1(0);
        } else {
            tfinancialrecord.setCommissionRate1(Double.valueOf(lineTxt.substring(89, 94).trim()));
        }
        tfinancialrecord.setCommissionAmount1(CalculateUtil.cal(lineTxt.substring(94, 105).trim()));

        if (!lineTxt.substring(105, 111).trim().isEmpty()) {
            tfinancialrecord.setCommissionType2(lineTxt.substring(105, 111).trim());
        }
        if (lineTxt.substring(111, 116).trim().isEmpty()) {
            tfinancialrecord.setCommissionRate2(0);
        } else {
            tfinancialrecord.setCommissionRate2(Double.valueOf(lineTxt.substring(111, 116).trim()));
        }
        tfinancialrecord.setCommissionAmount2(CalculateUtil.cal(lineTxt.substring(116, 127).trim()));

        tfinancialrecord.setCommissionType3(lineTxt.substring(127, 133).trim());
        if (lineTxt.substring(133, 138).trim().isEmpty()) {
            tfinancialrecord.setCommissionRate3(0);
        } else {
            tfinancialrecord.setCommissionRate3(Double.valueOf(lineTxt.substring(133, 138).trim()));
        }
        tfinancialrecord.setCommissionAmount3(CalculateUtil.cal(lineTxt.substring(138, 149).trim()));

        return tfinancialrecord;
    }


    TFormOfPaymentRecord setTFormOfPaymentRecord(String lineTxt) {
        TFormOfPaymentRecord tpaymentrecord = new TFormOfPaymentRecord();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(sdf.format(new Date()));
            tpaymentrecord.setImpDate(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//
        tpaymentrecord.settId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        tpaymentrecord.setFormOfPaymentType(lineTxt.substring(42, 52).trim());
        tpaymentrecord.setFormOfPaymentAmount(CalculateUtil.cal(lineTxt.substring(52, 63).trim()));
        tpaymentrecord.setFormOfPaymentAccountNumber(lineTxt.substring(63, 82).trim());
//				tpaymentrecord.setFormOfPaymentInformation(lineTxt.substring().trim());
        tpaymentrecord.setExpiryDate(lineTxt.substring(82, 86).trim());
        tpaymentrecord.setApprovalSource(lineTxt.substring(86, 87).trim());
        tpaymentrecord.setApprovalCode(lineTxt.substring(87, 93).trim());
        tpaymentrecord.setExtendedPaymentCode(lineTxt.substring(93, 96).trim());
        if (lineTxt.substring(96, 123).trim().isEmpty()) {
            tpaymentrecord.setCustomerFileReference("");
        } else {
            tpaymentrecord.setCustomerFileReference(lineTxt.substring(96, 123).trim());
        }

        tpaymentrecord.setCreditCardTransactionInform(lineTxt.substring(123, 148).trim());
        if (lineTxt.substring(148, 159).trim().isEmpty()) {
            tpaymentrecord.setAuthorizedAmount(0);
        } else {
            tpaymentrecord.setAuthorizedAmount(Double.valueOf(lineTxt.substring(148, 159).trim()));
        }
        tpaymentrecord.setCurrencyOfAuthorizedAmount(lineTxt.substring(159, 163).trim());
        tpaymentrecord.setCreditCardAddressVerificati(lineTxt.substring(163, 165).trim());

        return tpaymentrecord;
    }

    TExchangedDocumentInformati setTExchangedDocumentInformati(String lineTxt) {
        TExchangedDocumentInformati texchangeInfo = new TExchangedDocumentInformati();
//
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(sdf.format(new Date()));
            texchangeInfo.setImpDate(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        texchangeInfo.settId(Long.parseLong(lineTxt.substring(10, 25).trim()));
        if (lineTxt.substring(42, 57).trim().isEmpty()) {
            texchangeInfo.setTicket1OriginalTicketNumber("");
        } else {
            texchangeInfo.setTicket1OriginalTicketNumber(lineTxt.substring(42, 57).trim());
        }
        if (lineTxt.substring(57, 58).trim().isEmpty()) {
            texchangeInfo.setT1CheckNo(0);
        } else {
            texchangeInfo.setT1CheckNo(Integer.parseInt(lineTxt.substring(57, 58).trim()));
        }

        texchangeInfo.setTicket1RelatedTicketNumber(lineTxt.substring(58, 73).trim());
        texchangeInfo.setTicket1RelatedTicketNo(lineTxt.substring(73, 77).trim());
        texchangeInfo.setTicket1OriginalIssue(lineTxt.substring(77, 93).trim());
        texchangeInfo.setTicket2OriginalTicketNumber(lineTxt.substring(93, 108).trim());
        texchangeInfo.setT2CheckNo(Integer.parseInt(lineTxt.substring(108, 109).trim()));
        texchangeInfo.setTicket2RelatedTicketNumber(lineTxt.substring(109, 124).trim());
        texchangeInfo.setTicket2RelatedTicketNo(lineTxt.substring(124, 128).trim());
        texchangeInfo.setTicket2OriginalIssue(lineTxt.substring(128, 144).trim());
        texchangeInfo.setTicket3OriginalTicketNumber(lineTxt.substring(144, 159).trim());
        texchangeInfo.setT3CheckNo(Integer.parseInt(lineTxt.substring(159, 160).trim()));
        texchangeInfo.setTicket3RelatedTicketNumber(lineTxt.substring(160, 175).trim());
        texchangeInfo.setTicket3RelatedTicketNo(lineTxt.substring(175, 179).trim());
        texchangeInfo.setTicket3OriginalIssue(lineTxt.substring(179, 195).trim());
        texchangeInfo.setTicket4OriginalTicketNumber(lineTxt.substring(195, 210).trim());
        texchangeInfo.setT4CheckNo(Integer.parseInt(lineTxt.substring(210, 211).trim()));
        texchangeInfo.setTicket4RelatedTicketNumber(lineTxt.substring(211, 226).trim());
        texchangeInfo.setTicket4RelatedTicketNo(lineTxt.substring(226, 230).trim());
        texchangeInfo.setTicket4OriginalIssue(lineTxt.substring(230, 246).trim());
        texchangeInfo.setTicket5OriginalTicketNumber(lineTxt.substring(246, 261).trim());
        texchangeInfo.setT5CheckNo(Integer.parseInt(lineTxt.substring(261, 262).trim()));
        texchangeInfo.setTicket5RelatedTicketNumber(lineTxt.substring(262, 277).trim());
        texchangeInfo.setTicket5RelatedTicketNo(lineTxt.substring(277, 281).trim());
        texchangeInfo.setTicket5OriginalIssue(lineTxt.substring(281, 297).trim());
        texchangeInfo.setTicket6OriginalTicketNumber(lineTxt.substring(297, 312).trim());
        texchangeInfo.setT6CheckNo(Integer.parseInt(lineTxt.substring(312, 313).trim()));
        texchangeInfo.setTicket6RelatedTicketNumber(lineTxt.substring(313, 328).trim());
        texchangeInfo.setTicket6RelatedTicketNo(lineTxt.substring(328, 332).trim());
        texchangeInfo.setTicket6OriginalIssue(lineTxt.substring(332, 348).trim());
        texchangeInfo.setExchangeCertificate1Number(lineTxt.substring(348, 361).trim());
        texchangeInfo.setExchangeCertificate2Number(lineTxt.substring(361, 374).trim());
        texchangeInfo.setExchangeCertificate3Number(lineTxt.substring(374, 387).trim());

        return texchangeInfo;
    }


    /**
     * 取行字符串from～to间的子字符串，并进行格式化和设置默认值为""
     *
     * @param line
     * @param from
     * @param to
     * @return
     */
    String subStrTrimDef(String line, int from, int to) {
        return subStrTrimDef(line, from, to, "");
    }

    /**
     * 取行字符串from～to间的子字符串，并进行格式化和设置默认值
     *
     * @param line
     * @param from
     * @param to
     * @param def
     * @return
     */
    String subStrTrimDef(String line, int from, int to, String def) {
        String temp = line.substring(from, to).trim();
        return temp == null || temp.isEmpty() ? def : temp;
    }


    /**
     * 给map指定key的value值作加法
     *
     * @param map
     * @param key
     * @param value
     */
    void mapValueAdd(Map<Object, Object> map, String key, int value) {
        map.put(key, value + (int) get(map, key, 0));
    }

    /**
     * 给map指定key的value值作加法
     *
     * @param map
     * @param key
     * @param value
     */
    void mapValueAdd(Map<Object, Object> map, String key, double value) {
        map.put(key, value + (double) get(map, key, 0.0));
    }

}
